local cjson     = require "cjson"
local http      = require "http"
math.randomseed(os.time())
local wechatpay = {}

local function genRandomString(n)
    n = n or 32
    local chars = {
        "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
        "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
        "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
        "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
        "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
        "3", "4", "5", "6", "7", "8", "9"
    }
    local s = ""
    for i=1, n do
        local len = math.random(1, #chars)
        s = string.format("%s%s", s, chars[len])
    end
    return s
end

local function toUrlParams(tkeys,params)
    local str = '';
    for _, k in pairs(tkeys) do
        str = str .. k .. "=" .. params[k] .. "&"
    end
    return str
end

local function MakeSign(params,key)
    local tkeys = {}
    for k in pairs(params) do table.insert(tkeys, k) end
    table.sort(tkeys)
    local string = toUrlParams(tkeys,params)
    local key = "074922617df2ff4996761b9456cc8885"
    string = string .. "key=" .. key
    string = ngx.md5(string)
    string = string.upper(string)
    print("MakeSign aaa===>",string)
    return string
end

local function data_to_xml(params)
    local xml = "<xml>"
    for i, v in pairs(params) do
        if type(v) == "number" then
            xml = xml .. "<" .. i .. ">" ..v .. "</" .. i ..">"
        else
            xml = xml .. "<" .. i .. "><![CDATA[" .. v .. "]]></" .. i ..">"
        end
    end
    xml = xml .. "</xml>"
    return xml
end


local function unifiedOrder(params)
    local body = params.body
    local out_trade_no = params.out_trade_no
    local total_fee = params.total_fee
    local trade_type = params.trade_type
    local nonce_str = genRandomString()
    local spbill_create_ip = params.spbill_create_ip
    -- $this->body = $params['body'];
    -- $this->out_trade_no = $params['out_trade_no'];
    -- $this->total_fee = $params['total_fee'];
    -- $this->trade_type = $params['trade_type'];//交易类型 JSAPI | NATIVE |APP | WAP
    -- $this->nonce_str = $this->genRandomString();
    -- $this->spbill_create_ip = $params['spbill_create_ip'];
    local openid = params.openid
    local notify_url = ""

    local data = {}
    data.appid = "wxf0d6c5207faa8783"
    data.mch_id = "1633514059"
    data.nonce_str = nonce_str
    data.body = body
    data.out_trade_no = out_trade_no
    data.total_fee = total_fee
    data.spbill_create_ip = spbill_create_ip
    data.notify_url = notify_url
    data.trade_type = trade_type
    if openid then
        data.openid = params.openid
        data.sign_type = 'MD5'
    end
    local sign = MakeSign(data)
    data.sign = sign
    local xml = data_to_xml(data)
    print("unifiedOrder xml===>",xml)
    local url = "https://api.mch.weixin.qq.com/v3/pay/transactions/app"
    local response = http.post(url,xml)
    print("unifiedOrder response===>",response)
    -- $this->params['appid'] = $this->appid;
    -- $this->params['mch_id'] = $this->mch_id;
    -- $this->params['nonce_str'] = $this->nonce_str;
    -- $this->params['body'] = $this->body;
    -- $this->params['out_trade_no'] = $this->out_trade_no;
    -- $this->params['total_fee'] = $this->total_fee;
    -- $this->params['spbill_create_ip'] = $this->spbill_create_ip;
    -- $this->params['notify_url'] = $this->notify_url;
    -- $this->params['trade_type'] = $this->trade_type;
    -- if(isset($params['openid'])){
    --     $this->params['openid'] = $params['openid'];
    --     $this->params['sign_type'] = 'MD5';
    -- }
    -- //获取签名数据
    -- $this->sign = $this->MakeSign($this->params);
    -- $this->params['sign'] = $this->sign;
    -- $xml = $this->data_to_xml($this->params);
    -- Log::var_dump(array("xml"=>$xml));
    -- $response = CoroutineCurl::request(self::API_URL_HOST, self::UNIFIEDORDER_URL, 443, true, 'POST', $xml);
    -- Log::var_dump(array("response"=>$response));
    -- Log::dump(['s' => $response]);
    -- if (empty($response['result'])) {
    --     return false;
    -- }
    -- $result = $this->xml_to_data($response['result']);
    -- if (!empty($result['result_code']) && !empty($result['err_code'])) {
    --     return false;
    -- }
    -- return $result;
end

function wechatpay.getAppPaySign(params)
    local result = unifiedOrder(params)
    -- $result = $this->unifiedOrder($params);
    -- if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
    --     if(isset($params['openid'])){
    --         $data = $this->getJsPayParams($result['prepay_id']);
    --     }else{
    --         $data = $this->getAppPayParams($result['prepay_id']);
    --     }
    --     return $data;
    -- } else {
    --     $this->errorMsg = $result['return_msg'];
    --     return false;
    -- }
end



return wechatpay
